<template>
  <div class="baidu-map-container">
    <div id="baidu-map" class="map-view"></div>
    
    <div class="map-controls">
      <button @click="zoomIn" class="control-button" title="放大">
       <el-icon><Plus /></el-icon>
      </button>
      <button @click="zoomOut" class="control-button" title="缩小">
 <el-icon><Minus /></el-icon>
      </button>
      <button @click="locateMe" class="control-button" title="定位">
       <el-icon><Aim /></el-icon>
      </button>
    </div>
    
    <div class="location-info">
      <div v-if="isLocating" class="locating-message">
        <i class="fas fa-spinner fa-pulse"></i> 正在获取位置...
      </div>
      <div v-if="locationError" class="error-message">
        <i class="fas fa-exclamation-triangle"></i> {{ locationError }}
      </div>
      <div v-if="currentAddress" class="address-info">
        <p><el-icon><Location /></el-icon>{{ currentAddress }}</p>
        <p v-if="accuracy"><el-icon><Aim /></el-icon> 精度: ±{{ accuracy.toFixed(1) }}米</p>
      </div>
      <div class="coordinates" v-if="currentPosition">
        <p><strong>经度:</strong> {{ currentPosition.lng.toFixed(6) }}</p>
        <p><strong>纬度:</strong> {{ currentPosition.lat.toFixed(6) }}</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { updateLocation } from '@/api/map' // 导入API方法
 // 组件props
const props = defineProps({
  initialLocation: {
    type: Object as () => { lng: number; lat: number } | null,
    default: null
  },
  autoLocate: {
    type: Boolean,
    default: true
  }
})
const emit = defineEmits(['location-updated'])
// 组件状态
const mapInstance = ref<any>(null)
const currentPosition = ref<{ lng: number; lat: number } | null>(null)
const currentAddress = ref('')
const accuracy = ref(0)
const isLocating = ref(false)
const locationError = ref('')
const marker = ref<any>(null)

// 加载百度地图API
const loadBaiduMapScript = () => {
  return new Promise<void>((resolve, reject) => {
    if ((window as any).BMap) {
      return resolve()
    }

    const script = document.createElement('script')
    script.src = `https://api.map.baidu.com/api?v=3.0&ak=gYEg2UGSVhaHdnOJhwI9BLKSivmYUDIj&callback=baiduMapInit`
    script.async = true
    script.defer = true

    // 定义回调函数
    ;(window as any).baiduMapInit = () => {
      resolve()
      delete (window as any).baiduMapInit
    }

    script.onerror = (error) => {
      reject(new Error('百度地图加载失败'))
    }

    document.head.appendChild(script)
  })
}

// 初始化地图
const initMap = () => {
  return new Promise<void>((resolve) => {
    if (!(window as any).BMap) {
      console.error('百度地图API未加载')
      return resolve()
    }

    nextTick(() => {
      // 创建地图实例
      mapInstance.value = new (window as any).BMap.Map("baidu-map")
      
      // 添加地图控件
      mapInstance.value.addControl(new (window as any).BMap.NavigationControl())
      mapInstance.value.addControl(new (window as any).BMap.ScaleControl())
      
      // 设置默认中心点和缩放级别
      const defaultPoint = new (window as any).BMap.Point(116.404, 39.915)
      mapInstance.value.centerAndZoom(defaultPoint, 15)
      
      // 启用滚轮缩放
      mapInstance.value.enableScrollWheelZoom()
      
      resolve()
    })
  })
}

// 获取当前位置
const getCurrentLocation = (): Promise<GeolocationPosition> => {
  return new Promise((resolve, reject) => {
    if (!navigator.geolocation) {
      reject(new Error('浏览器不支持地理位置功能'))
      return
    }

    navigator.geolocation.getCurrentPosition(
      (position) => resolve(position),
      (error) => reject(error),
      {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 0
      }
    )
  })
}

// 反向地理编码（坐标转地址）
const reverseGeocode = async (lat: number, lng: number) => {
  return new Promise<string>((resolve) => {
    if (!(window as any).BMap) {
      console.error('百度地图API未加载')
      return resolve('')
    }

    const geoc = new (window as any).BMap.Geocoder()
    const point = new (window as any).BMap.Point(lng, lat)

    geoc.getLocation(point, (result: any) => {
      resolve(result?.address || '')
    })
  })
}

// 在地图上显示位置
const showLocationOnMap = async (lat: number, lng: number) => {
  if (!mapInstance.value) return

  // 更新当前位置
  currentPosition.value = { lng, lat }
  
  // 获取地址信息
  currentAddress.value = await reverseGeocode(lat, lng)
  
  // 清除旧标记
  if (marker.value) {
    mapInstance.value.removeOverlay(marker.value)
  }
  
  // 创建新点
  const point = new (window as any).BMap.Point(lng, lat)
  mapInstance.value.centerAndZoom(point, 18)
  
  // 添加标记
  marker.value = new (window as any).BMap.Marker(point)
  mapInstance.value.addOverlay(marker.value)
  
  // 添加信息窗口
  const infoContent = `
    <div class="map-info-window">
      <p><strong>您的位置</strong></p>
      <p>${currentAddress.value || '未知地址'}</p>
      <p>经度: ${lng.toFixed(6)}</p>
      <p>纬度: ${lat.toFixed(6)}</p>
      ${accuracy.value ? `<p>精度: ±${accuracy.value.toFixed(1)}米</p>` : ''}
    </div>
  `

  const infoWindow = new (window as any).BMap.InfoWindow(infoContent)
  marker.value.addEventListener("click", () => {
    mapInstance.value.openInfoWindow(infoWindow, point)
  })
  mapInstance.value.openInfoWindow(infoWindow, point)
}

// 定位用户位置
const locateMe = async () => {
  isLocating.value = true
  locationError.value = ''

  try {
    const position = await getCurrentLocation()
    accuracy.value = position.coords.accuracy
    
    // 显示位置在地图上
    await showLocationOnMap(position.coords.latitude, position.coords.longitude)
    
    // 获取地址信息
    const address = await reverseGeocode(position.coords.latitude, position.coords.longitude)
    currentAddress.value = address
    
    // 准备发送到后端的数据
    const locationData = {
      lastLocationPoint: `${position.coords.longitude},${position.coords.latitude}`,
      lastLocationAt: new Date().toISOString(),
      location: address
    }
    
    // 调用API更新位置
    try {
      await updateLocation(locationData)
      emit('location-updated', locationData)
    } catch (error) {
      console.error('位置更新失败:', error)
      locationError.value = '位置信息保存失败'
    }
    
  } catch (error) {
    console.error('获取位置失败:', error)
    locationError.value = error instanceof GeolocationPositionError
      ? getGeolocationErrorText(error.code)
      : String(error)
  } finally {
    isLocating.value = false
  }
}

// 错误代码转文字
const getGeolocationErrorText = (code: number) => {
  switch (code) {
    case GeolocationPositionError.PERMISSION_DENIED:
      return '用户拒绝了位置请求，请在浏览器设置中修改权限'
    case GeolocationPositionError.POSITION_UNAVAILABLE:
      return '无法获取位置信息，请检查GPS或网络连接'
    case GeolocationPositionError.TIMEOUT:
      return '获取位置超时，请重试'
    default:
      return '获取位置时发生未知错误'
  }
}

// 地图缩放控制
const zoomIn = () => {
  if (mapInstance.value) {
    mapInstance.value.zoomIn()
  }
}

const zoomOut = () => {
  if (mapInstance.value) {
    mapInstance.value.zoomOut()
  }
}

// 组件挂载时初始化
onMounted(async () => {
  try {
    // 加载百度地图API
    await loadBaiduMapScript()
    
    // 初始化地图
    await initMap()
    
    // 如果有初始位置，显示初始位置
    if (props.initialLocation) {
      await showLocationOnMap(
        props.initialLocation.lat,
        props.initialLocation.lng
      )
    }
    
    // 如果开启自动定位，尝试获取当前位置
    if (props.autoLocate) {
      await locateMe()
    }
    
  } catch (error) {
    console.error('地图初始化失败:', error)
    locationError.value = '地图初始化失败，请刷新页面重试'
  }
})

// 组件卸载时清理
onUnmounted(() => {
  if (mapInstance.value) {
    mapInstance.value.destroy()
    mapInstance.value = null
  }
})
</script>

<style scoped>
.baidu-map-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.map-view {
  width: 100%;
  height: 450px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  border: 1px solid #e0e0e0;
}

.map-controls {
  position: absolute;
  top: 20px;
  right: 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  z-index: 1000;
}

.control-button {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: white;
  border: 1px solid #ddd;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.2s;
}

.control-button:hover {
  background-color: #f5f5f5;
  transform: scale(1.05);
}

.control-button i {
  font-size: 14px;
  color: #333;
}

.location-info {
  margin-top: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.locating-message {
  color: #666;
  display: flex;
  align-items: center;
  gap: 8px;
}

.error-message {
  color: #f44336;
  display: flex;
  align-items: center;
  gap: 8px;
}

.address-info {
  color: #2e7d32;
}

.address-info p {
  margin: 8px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.coordinates {
  margin-top: 10px;
  font-family: 'Courier New', monospace;
  color: #333;
}

.coordinates p {
  margin: 5px 0;
}

@media (max-width: 768px) {
  .map-view {
    height: 350px;
  }
}

@media (max-width: 480px) {
  .map-view {
    height: 280px;
  }
  
  .map-controls {
    top: 10px;
    right: 10px;
  }
  
  .control-button {
    width: 32px;
    height: 32px;
  }
}
</style>

<style>
/* 全局样式，用于地图信息窗口 */
.map-info-window {
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  padding: 10px;
  min-width: 200px;
}

.map-info-window p {
  margin: 8px 0;
  line-height: 1.4;
}

.map-info-window strong {
  color: #1a73e8;
}
</style>